package com.jlkf.service.impl;

import com.aliyun.mns.common.utils.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlkf.common.Page;
import com.jlkf.dao.*;
import com.jlkf.pojo.*;
import com.jlkf.service.DriverService;
import com.jlkf.service.util.LanguageUtils;
import com.jlkf.service.util.RegexUtil;
import com.jlkf.service.util.StringTools;
import com.platform.server.response.response.pojo.ReturnData;

import io.practiceinsight.pinpayments.pojo.ErrorMessage;
import io.practiceinsight.pinpayments.pojo.ErrorResponseCard;
import io.practiceinsight.pinpayments.pojo.ResponseBrankAccount;
import io.practiceinsight.pinpayments.pojo.ResponseRecipients;
import io.practiceinsight.pinpayments.utils.PinPayHttpUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;

@Service
@Transactional
public class DriverServiceImpl implements DriverService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMessageMapper userMessageMapper;
    @Autowired
    private UserBrankMapper userBrankMapper;
    @Autowired
    private DriverAccessoryMapper driverAccessoryMapper;
    @Autowired
    private StarRemarkMapper starRemarkMapper;
    @Autowired
    private SugFeedbackMapper sugFeedbackMapper;
    @Autowired
    private DriverTurnoverMapper driverTurnoverMapper;
    @Autowired
    private OrderItemsMapper orderItemsMapper;
    @Autowired
	private ConfigManagerMapper configManagerMapper;
    @Autowired
	private CarCaculationMapper carCaculationMapper; 
    @Autowired
    private UserConfirmTheOrderingMapper userConfirmTheOrderingMapper;
    @Autowired
	private JedisPool jedisPool; 
    
    //司机端用户信息
    public Map<String, Object> getUserInfo(Long uid) {
        Map<String, Object> data = new HashMap<>();
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> ma = new HashMap();
        User user = userMapper.selectByPrimaryKey(uid);
        user.setPassword(null);
        data.put("user", user);
        map.put("uId", uid);
//        map.put("isDefault", 1);
        List<UserBrank> list=userBrankMapper.getUserBrank(map);
        UserBrank ub = null;
        if(list.size()>0){
        	ub = list.get(0);
        }
       ma.put("driverId", uid);
       Jedis jedis = null;
			if(jedis==null){
				jedis =jedisPool.getResource();
			}
    try {
    	   List<UserConfirmTheOrdering> ll= userConfirmTheOrderingMapper.getUserConfirmTheOrdering(ma);
           if(ll.size()>0){
        	   if(user.getNotOrder()==2){
        		   Calendar calendar = new GregorianCalendar();
        			calendar.setTime(ll.get(0).getCreateTime());
        			calendar.add(calendar.MINUTE, 15);
        			Date date=calendar.getTime();
        		   user.setPunishmentOfTime(date.getTime());//结束时间
        	   }
        	   if(user.getNotOrder()==4){
        		   int bantime=0;//司机当天取消超过多少次会被禁止工作多少分钟
//        			List<ConfigManager> list1=configManagerMapper.getList();//默认都会有一条数据
        		 
    				String configManager=jedis.get("configManager");
    				ConfigManager cm=null;
    				if(StringTools.isEmpty(configManager)){
    					 cm = configManagerMapper.selectByPrimaryKey(1);
    						JSONObject jo = JSONObject.fromObject(cm);
    						jedis.set("configManager", jo.toString());
    						bantime = cm.getBantime();
    				}else{
    					JSONObject jo = JSONObject.fromObject(configManager);
    					cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
    					bantime = cm.getBantime();
    				}
    				
//        			bantime = list1.get(0).getBantime();
        		   Calendar calendar = new GregorianCalendar();
        			calendar.setTime(ll.get(0).getCreateTime());
        			calendar.add(calendar.MINUTE, bantime);
        			Date date=calendar.getTime();
        		   user.setPunishmentOfTime(date.getTime());//结束时间
        	   }
        	   
           }
            data.put("ub", ub);
            List<DriverAccessory> dl= driverAccessoryMapper.getUserCars(uid);
            data.put("carCount", dl.size());
            return data;
	} catch (Exception e) {
		e.printStackTrace();
		return data;
	}finally {
		if(jedis!=null){
			jedis.close();
		}
	}
    }

    //用户通知
    public Object getUserNotices(Long uid, Page page) {
        ReturnData result = new ReturnData();
        Map<String, Object> data = new HashMap<>();
        //分页
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<UserMessage> list = userMessageMapper.getUserNotices(uid);
        for(UserMessage um:list){
        	um.setIsRead(1);
        	userMessageMapper.updateByPrimaryKeySelective(um);
        }
        PageInfo<UserMessage> info = new PageInfo<>(list);
        //封装返回信息
        result.setPageNo(info.getPageNum());
        result.setTotalPage(info.getPages());
        result.setTotalRecord((int) info.getTotal());
        data.put("notices", list);
        result.setData(data);
        result.setMsg("success");
        result.setCode(200);
        return result;
    }
    

    //更新用户
    public Object updateUser(User user) {
    	int n=userMapper.updateByPrimaryKeySelective(user);
    	if(n==0){
    		return new ReturnData(201,"fail");
    	}
        return new ReturnData(200,"success");
    }

    //添加银行卡
    public Object addCard(UserBrank bank) {
        bank.setCreateTime(new Date());
        bank.setIsDefault(1);
       Map<String,Object> map = new HashMap<>();
     /*  map.put("ubBrankNo", bank.getUbBrankNo());//银行卡号
       List<UserBrank> list=userBrankMapper.getUserBrank(map);
       if(list.size()>0){
    	   return new ReturnData(201,"New Bank Card Added");
       }*/
         // 银行账户API
       /**
        * 银行账户API允许您安全地存储银行账户信息以换取银行账户令牌。然后可以使用此令牌使用收件人API创建收件人。
			银行账户令牌只能使用一次来创建收件人。如果令牌没有被使用，令牌会在一个月后自动过期。
			
			使用此API存储银行帐户详细信息时有两种身份验证方式：
			
			在您的安全环境中，使用您的一个秘密API密钥使用HTTP基本访问验证。
			在不安全的环境中，如Web浏览器或移动应用程序，通过使用其中一个可发布的API密钥。
			这个API支持JSONP。
        */
       if(!StringTools.isEmpty(bank.getTheCardholder())){
			String theCardHolder = bank.getTheCardholder();
			theCardHolder=theCardHolder.trim();
			if(theCardHolder.indexOf(" ") != -1){
			}else{
				return new ReturnData(205, LanguageUtils.returnLan(1, "cardholder_name"));
			}
		}
//       bank.setTheCardholder(bank.getBrankName());
       map.put("ids", bank.getuId());
       Map<String,String> brankAccount = new HashMap<>();
       List<User> u= userMapper.getNameAndTel(map);//查询司机的信息  为了拿到司机的邮箱
       if(u.size()>0){
    	   brankAccount.put("email", u.get(0).getEmail());//收件人的电子邮件地址。
       }
       brankAccount.put("bank_account[name]", bank.getTheCardholder());//账户持有人的姓名（例如John Smith）。
       brankAccount.put("bank_account[bsb]", bank.getBsb());//bsb
       brankAccount.put("bank_account[number]", bank.getUbBrankNo());//银行卡号
       Map<String,Object> resut= PinPayHttpUtils.sendPinPayCreateRecipientPost(brankAccount);
       if(resut.get("code")!=null&&(int)resut.get("code")==201){
    	   ResponseRecipients rc=(ResponseRecipients) resut.get("obj");
			bank.setAvoidCloseToPayToken(rc.getResponse().getToken());//
			int num = userBrankMapper.insertSelective(bank);
			if (num == 0) {
				return new ReturnData(202, "fail");
			}
			int n=userBrankMapper.insertSelective(bank);
		       if(n==0){
		    	   return new ReturnData(202,"fail");
		       }
		  
		}else if(resut.get("code")!=null&&(int)resut.get("code")==422){
			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
			String error="";
			if(rc!=null){
				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc.getMessages()), ErrorMessage.class);
             for(ErrorMessage ee:liMessage){
           	  error+=ee.getMessage()+" ; "; 
             }
			}
			return new ReturnData(204, error);
		}
       return  new ReturnData(200,"success");
    }

    //车辆列表
    public Object getUserCars(Long uid) {
        List<DriverAccessory> cars = driverAccessoryMapper.getUserCars(uid);
        return new ReturnData(cars);
    }

    //车辆信息详情
    public Object carInfo(Long carid) {
        DriverAccessory car = driverAccessoryMapper.selectByPrimaryKey(carid);
        return new ReturnData(car);
    }

    //评价乘客
    public Object commentPassenger(StarRemark star) {
        star.setType(1);//司机评价
        star.setCreateTime(new Date());
        return new ReturnData(starRemarkMapper.insertSelective(star));
    }

    //评价反馈
    public Object feedback(SugFeedback feedback) {
        feedback.setMsgdate(new Date());
        return sugFeedbackMapper.insertSelective(feedback);
    }

    //添加车辆
    public Object addCar(DriverAccessory car) {
        car.setUpTime(new Date());
        return driverAccessoryMapper.insertSelective(car);
    }

    //我的账单
    public Object mybill(Long uid, String mark,Integer len) {
        Map<String,Object> data = new HashMap<>();
        //参数准备
        DateTime time = new DateTime(mark);
        DriverTurnover params = new DriverTurnover();
        params.setDriverId(uid);
        List<Map> bills = new ArrayList<>();
       len=len==null?5:len;
        boolean flag = false;
        for (int i = 0; i <len ; i++) {
        	
        	params.setMonths(time.getYear()+"-"+time.getMonthOfYear());
//            params.setMonth(time.minusMonths(i).toDate());
            DriverTurnover temp = driverTurnoverMapper.getBillByMonth(params);
            if(temp != null){
//                bills.add(temp);
            	Map<String,Object> m=change(temp);
                bills.add(m);
                Map<String,Object> obj= monthbill(temp.getId());
                data.put("bill",obj);
            }	
        }
        data.put("bills",bills);
        return new ReturnData(data);
    }
    private Map<String,Object> monthbill(DriverTurnover m){
    	DecimalFormat df = new DecimalFormat("###0.00");
    	Map<String,Object> mm=new HashMap<>();
    	 mm.put("id", m.getId());
    	 mm.put("driverId", m.getDriverId());
    	 mm.put("turnover", df.format(m.getTurnover()));
    	 mm.put("contributionAmount", df.format(m.getContributionAmount()));
    	 mm.put("ratio", df.format(m.getRatio()));
    	 mm.put("status", m.getStatus());
    	 mm.put("createTime", m.getCreateTime().getTime());
    	 mm.put("tip", df.format(m.getTip()));
    	 mm.put("cleanness", df.format(m.getCleanness()));
    	 mm.put("roadPrice", df.format(m.getRoadPrice()));
    	 mm.put("checkoutTime", m.getCheckoutTime());
    	 mm.put("remark", m.getRemark());
    	 mm.put("settlement", m.getSettlement());
    	 mm.put("month", m.getMonth());
    	 mm.put("settlementTime", m.getSettlementTime());
    	 mm.put("orderNum", m.getOrderNum());
    	 mm.put("totalServiceTime", m.getTotalServiceTime());
    	 mm.put("monthlyPlatformCollection", df.format(m.getMonthlyPlatformCollection()));
    	 mm.put("driverName", m.getDriverName());
    	 mm.put("driverPhone", m.getDriverPhone());
    	 
		return mm;
    }
    private Map<String,Object> change(DriverTurnover m){
    	DecimalFormat df = new DecimalFormat("###0.00");
    	Map<String,Object> mm=new HashMap<>();
    	  mm.put("id", m.getId());
    	  Object turnover= m.getTurnover()==null?0:m.getTurnover();
    	  mm.put("turnover", df.format(turnover));
    	 Object ca= m.getContributionAmount()==null?0:m.getContributionAmount();
    	  mm.put("contributionAmount", df.format(ca));
    	  mm.put("month", com.jlkf.service.util.DateUtil.format(m.getMonth(), "yyyy-MM-dd"));
		return mm;
    }

    //我的账单-月
    public Map<String,Object> monthbill(Long id) {
        return monthbill(driverTurnoverMapper.selectByPrimaryKey(id));
    }

	@Override
	public Object billingDetails(String startTime, String endTime, Long driverId,Integer pageNo,Integer pageSize) {
		Map<String,Object> map = new HashMap<>();
		Map<String,Object> result = new HashMap<>();
		map.put("dirberId", driverId);
		if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
			map.put("startTime", startTime);
			map.put("endTime", endTime);
		}
		if(RegexUtil.isNull(pageNo)){
			pageNo=1;
		}
		if(RegexUtil.isNull(pageSize)){
			pageSize=10;
		}
		DecimalFormat df = new DecimalFormat("######0.00");
		try {
			PageHelper.startPage(pageNo, pageSize);
			List<OrderItems> list=orderItemsMapper.getOrderItems(map);
			result.put("orderList", list);//订单详情
			List<CarCaculation> ccmlist=carCaculationMapper.getCarCaculation(map);//计价规则
			Double totalMoney = 0.0;//总金额   
			Double commission=0.0;//提成金额
			for(OrderItems oi:list){
			  	for(CarCaculation cc:ccmlist){
			  		if(oi.getCarType()==cc.getCarType()){//收费标砖与订单用车类型一致
			  			Double totalPrice = oi.getTotalPrice().doubleValue();
				  		commission+=totalPrice*cc.getFabCommission();//平台收取的佣金比例  0.2
				  		totalMoney += totalPrice;
			  		}
			  	}
			}
			result.put("totalMoney", df.format(totalMoney));
			result.put("commission", df.format(commission));
			return new ReturnData(result,200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

	@Override
	public ReturnData setDefaultVehicle(Long driverId, Long carId,Integer language) {
		boolean flag=true;
		if(RegexUtil.isNull(language)){
			return new ReturnData(201,"Language cannot be empty");
		}
		if(RegexUtil.isNull(driverId)){
			return new ReturnData(201,"The driver id cannot be empty");
		}
		if(RegexUtil.isNull(carId)){
			return new ReturnData(201,"Vehicle id cannot be empty");
		}
		try {
			List<DriverAccessory> list = driverAccessoryMapper.getUserCars(driverId);//查询司机的车辆
			for(DriverAccessory da:list){
				int nums=(int) (carId-da.getId());
				if(nums==0){//车的id一致  那么将司机的这个车设为默认用车 将别的车 更新为非默认
					da.setIsDefault(1);//默认使用 1 默认 2不是默认
					da.setIsUse(1);//今日是否在用 1正在使用 2未用
					da.setServerStatus(0);//服务状态 0空闲 1服务中
				}else{
					da.setIsDefault(2);
					da.setIsUse(2);//今日是否在用 1正在使用 2未用
					da.setServerStatus(1);
				}
				int num=driverAccessoryMapper.updateByPrimaryKeySelective(da);
				if(num==0){
					flag=false;
					break;
				}
			}
			if(flag){
				return new ReturnData(200,LanguageUtils.returnLan(language, "set_up_the_success"));
			}
			return new ReturnData(209,LanguageUtils.returnLan(language, "set_up_the_fail"));
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

	@Override
	public Object carServiceType( Long carId, String serverType,Integer language) {
		if(RegexUtil.isNull(language)){
			return new ReturnData(201,"Language cannot be empty");
		}
		if(RegexUtil.isNull(carId)){
			return new ReturnData(201,"Vehicle id cannot be empty");
		}
		if(RegexUtil.isNull(serverType)){
			return new ReturnData(201,"The service type cannot be empty");
		}
		try {
			DriverAccessory driverAccessory=driverAccessoryMapper.selectByPrimaryKey(carId);
			if(driverAccessory==null){
				return new ReturnData(201,LanguageUtils.returnLan(language, "vehicle_not_found"));
			}
			driverAccessory.setOpenServerType(serverType);//更新该车服务的类型 司机接单服务的车辆类型
			int num=driverAccessoryMapper.updateByPrimaryKeySelective(driverAccessory);
			if(num==0){
				return new ReturnData(208,LanguageUtils.returnLan(language, "set_up_the_fail"));
			}
			return new ReturnData(200,LanguageUtils.returnLan(language, "set_up_the_success"));
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}
	@Override
	public Object updatecard(UserBrank bank) {
		 Map<String,Object> map = new HashMap<>();
		 Map<String,String> brankAccount = new HashMap<>();
		try {
			  map.put("ids", bank.getuId());
			  if(!StringTools.isEmpty(bank.getTheCardholder())){
					String theCardHolder = bank.getTheCardholder();
					theCardHolder=theCardHolder.trim();
					if(theCardHolder.indexOf(" ") != -1){
					}else{
						return new ReturnData(205, LanguageUtils.returnLan(1, "cardholder_name"));
					}
				}
			  List<User> u= userMapper.getNameAndTel(map);//查询司机的信息  为了拿到司机的邮箱
		       if(u.size()>0){
		    	   brankAccount.put("email", u.get(0).getEmail());//收件人的电子邮件地址。
		       }
		       brankAccount.put("bank_account[name]", bank.getTheCardholder());//账户持有人的姓名（例如John Smith）。
		       brankAccount.put("bank_account[bsb]", bank.getBsb());//bsb
		       brankAccount.put("bank_account[number]", bank.getUbBrankNo());//银行卡号
		       Map<String,Object> resut= PinPayHttpUtils.sendPinPayCreateRecipientPost(brankAccount);
		       if(resut.get("code")!=null&&(int)resut.get("code")==201){
		    	   ResponseRecipients rc=(ResponseRecipients) resut.get("obj");
					bank.setAvoidCloseToPayToken(rc.getResponse().getToken());//
					if(bank.getUbId()!=null){//银行卡id
						int num=userBrankMapper.updateByPrimaryKeySelective(bank);
						if(num==0){
							return new ReturnData(201,"update fail");
						}
					}else{
						 map.put("uId", bank.getuId());
						 List<UserBrank> list=userBrankMapper.getUserBrank(map);
					       if(list.size()>0){
					    	   return new ReturnData(201,"New Bank Card Added");
					       }
						bank.setCreateTime(new Date());
						int num = userBrankMapper.insertSelective(bank);
						if(num==0){
							return new ReturnData(201,"update fail");
						}
					}
				}else if(resut.get("code")!=null&&(int)resut.get("code")==422){
					ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
					String error="";
					if(rc!=null){
						List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc.getMessages()), ErrorMessage.class);
		             for(ErrorMessage ee:liMessage){
		           	  error+=ee.getMessage()+" ; "; 
		             }
					}
					return new ReturnData(204, error);
				}
			return new ReturnData(200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

	@Override
	public Object notRead(Long uId) {
		String str=userMessageMapper.getNotReadCount(uId);
		if(str==null||str.equals("0")){
			str="0";
		}
		return new ReturnData(str,200,"success");
	}
}
